"""
版本管理API响应Schema
用于定义API响应的数据模型，统一响应格式
"""
from datetime import datetime
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
from app.models.version import (
    Version,
    VersionTaskRelation,
    VersionDefectRelation,
    VersionRequirement,
    ReleaseRecord,
    ReleaseType,
    Environment,
    ReleaseStatus,
    RelationType
)


# ========== 版本响应 Schema ==========

class VersionBasic(BaseModel):
    """版本基础信息（用于列表和摘要）"""
    id: str = Field(..., description="版本ID")
    name: str = Field(..., description="版本名称")
    version_number: str = Field(..., description="版本号")
    description: Optional[str] = Field(None, description="版本描述")
    project_id: str = Field(..., description="项目ID")
    project_name: Optional[str] = Field(None, description="项目名称")
    start_date: Optional[datetime] = Field(None, description="版本开始时间")
    end_date: Optional[datetime] = Field(None, description="版本结束时间")
    status: str = Field(..., description="版本状态")
    release_type: Optional[str] = Field(None, description="发布类型")
    environment: Optional[str] = Field(None, description="发布环境")
    planned_release_date: Optional[datetime] = Field(None, description="计划发布时间")
    actual_release_date: Optional[datetime] = Field(None, description="实际发布时间")
    planned_work_hours: float = Field(0.0, ge=0, description="规划工时（小时）")
    release_notes: Optional[str] = Field(None, description="发布说明")
    created_by: str = Field(..., description="创建者ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")

    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.isoformat() if v else None
        }


class VersionWithStats(VersionBasic):
    """带统计信息的版本模型"""
    task_count: int = Field(default=0, description="关联任务数量")
    defect_count: int = Field(default=0, description="关联缺陷数量")
    requirement_count: int = Field(default=0, description="关联需求数量")
    release_count: int = Field(default=0, description="发布记录数量")
    completed_task_count: Optional[int] = Field(None, description="已完成任务数量")
    fixed_defect_count: Optional[int] = Field(None, description="已修复缺陷数量")
    completed_requirement_count: Optional[int] = Field(None, description="已完成需求数量")


class TaskRelationInfo(BaseModel):
    """任务关联信息"""
    id: str = Field(..., description="关联ID")
    version_id: str = Field(..., description="版本ID")
    task_id: str = Field(..., description="任务ID")
    requirement_id: Optional[str] = Field(None, description="关联的需求ID")
    requirement_title: Optional[str] = Field(None, description="关联的需求名称")
    task_title: Optional[str] = Field(None, description="任务标题")
    task_status: Optional[str] = Field(None, description="任务状态")
    task_priority: Optional[str] = Field(None, description="任务优先级")
    task_assignee: Optional[str] = Field(None, description="任务负责人")
    relation_type: str = Field(..., description="关联类型")
    relation_notes: Optional[str] = Field(None, description="关联备注")
    associated_by: Optional[str] = Field(None, description="关联创建者")
    associated_by_name: Optional[str] = Field(None, description="关联创建者名称")
    associated_at: Optional[datetime] = Field(None, description="关联时间")

    class Config:
        from_attributes = True


class DefectRelationInfo(BaseModel):
    """缺陷关联信息"""
    id: str = Field(..., description="关联ID")
    version_id: str = Field(..., description="版本ID")
    defect_id: str = Field(..., description="缺陷ID")
    requirement_id: Optional[str] = Field(None, description="关联的需求ID")
    requirement_title: Optional[str] = Field(None, description="关联的需求名称")
    task_id: Optional[str] = Field(None, description="关联的任务ID")
    task_title: Optional[str] = Field(None, description="关联的任务名称")
    parent_defect_id: Optional[str] = Field(None, description="父缺陷ID")
    parent_defect_title: Optional[str] = Field(None, description="父缺陷标题")
    defect_title: Optional[str] = Field(None, description="缺陷标题")
    defect_status: Optional[str] = Field(None, description="缺陷状态")
    defect_priority: Optional[str] = Field(None, description="缺陷优先级")
    defect_severity: Optional[str] = Field(None, description="缺陷严重程度")
    relation_type: str = Field(..., description="关联类型")
    relation_notes: Optional[str] = Field(None, description="关联备注")
    associated_by: Optional[str] = Field(None, description="关联创建者")
    associated_by_name: Optional[str] = Field(None, description="关联创建者名称")
    associated_at: Optional[datetime] = Field(None, description="关联时间")

    class Config:
        from_attributes = True


class RequirementRelationInfo(BaseModel):
    """需求关联信息"""
    id: str = Field(..., description="关联ID")
    version_id: str = Field(..., description="版本ID")
    requirement_id: str = Field(..., description="需求ID")
    requirement_title: Optional[str] = Field(None, description="需求标题")
    requirement_status: Optional[str] = Field(None, description="需求状态")
    requirement_priority: Optional[str] = Field(None, description="需求优先级")
    relation_type: str = Field(..., description="关联类型")
    relation_notes: Optional[str] = Field(None, description="关联备注")
    associated_by: Optional[str] = Field(None, description="关联创建者")
    associated_by_name: Optional[str] = Field(None, description="关联创建者名称")
    associated_at: Optional[datetime] = Field(None, description="关联时间")

    class Config:
        from_attributes = True


class ReleaseRecordInfo(BaseModel):
    """发布记录信息"""
    id: str = Field(..., description="发布记录ID")
    version_id: str = Field(..., description="版本ID")
    release_type: str = Field(..., description="发布类型")
    environment: str = Field(..., description="发布环境")
    status: str = Field(..., description="发布状态")
    release_date: Optional[datetime] = Field(None, description="发布时间")
    rollback_date: Optional[datetime] = Field(None, description="回滚时间")
    notes: Optional[str] = Field(None, description="发布说明")
    created_by: Optional[str] = Field(None, description="创建者ID")
    created_at: Optional[datetime] = Field(None, description="创建时间")
    updated_at: Optional[datetime] = Field(None, description="更新时间")

    class Config:
        from_attributes = True


class VersionDetail(VersionWithStats):
    """版本详情响应模型"""
    tasks: List[Dict[str, Any]] = Field(default_factory=list, description="关联任务列表")
    defects: List[Dict[str, Any]] = Field(default_factory=list, description="关联缺陷列表")
    requirements: List[Dict[str, Any]] = Field(default_factory=list, description="关联需求列表")
    release_records: List[Dict[str, Any]] = Field(default_factory=list, description="发布记录列表")
    release_config: Optional[Dict[str, Any]] = Field(None, description="发布配置")
    metadata: Optional[Dict[str, Any]] = Field(None, description="版本元数据")


# ========== 版本统计 Schema ==========

class VersionStatistics(BaseModel):
    """版本统计模型"""
    total_versions: int = Field(default=0, description="总版本数")
    status_distribution: Dict[str, int] = Field(default_factory=dict, description="状态分布")
    release_type_distribution: Dict[str, int] = Field(default_factory=dict, description="发布类型分布")
    environment_distribution: Dict[str, int] = Field(default_factory=dict, description="环境分布")
    monthly_creation_trend: List[Dict[str, Any]] = Field(default_factory=list, description="月度创建趋势")
    project_version_counts: List[Dict[str, Any]] = Field(default_factory=list, description="项目版本数量")
    average_tasks_per_version: float = Field(default=0.0, description="平均任务数")
    average_defects_per_version: float = Field(default=0.0, description="平均缺陷数")
    release_success_rate: float = Field(default=0.0, description="发布成功率")


class VersionAnalyticsOverview(BaseModel):
    """版本分析概览"""
    summary: Dict[str, Any] = Field(..., description="汇总信息")
    trend_analysis: List[Dict[str, Any]] = Field(default_factory=list, description="趋势分析")
    quality_metrics: Dict[str, Any] = Field(default_factory=dict, description="质量指标")
    generated_at: datetime = Field(default_factory=datetime.utcnow, description="生成时间")


class VersionProgressStats(BaseModel):
    """版本进度统计"""
    total: int = Field(0, description="总数量")
    completed: int = Field(0, description="已完成数量")


class VersionOverviewItem(VersionWithStats):
    """版本总览条目"""
    progress: float = Field(0.0, ge=0, le=100, description="综合进度百分比")
    requirement_stats: VersionProgressStats = Field(default_factory=VersionProgressStats, description="需求统计")
    task_stats: VersionProgressStats = Field(default_factory=VersionProgressStats, description="任务统计")
    defect_stats: VersionProgressStats = Field(default_factory=VersionProgressStats, description="缺陷统计")


class VersionOverviewResponse(BaseModel):
    """版本总览响应"""
    items: List[VersionOverviewItem] = Field(default_factory=list, description="版本列表")
    total: int = Field(0, description="总数量")


class QualityMetrics(BaseModel):
    """质量指标模型"""
    version_id: str = Field(..., description="版本ID")
    version_name: Optional[str] = Field(None, description="版本名称")
    version_number: Optional[str] = Field(None, description="版本号")
    total_defects: int = Field(default=0, description="总缺陷数")
    critical_defects: int = Field(default=0, description="严重缺陷数")
    high_defects: int = Field(default=0, description="高优先级缺陷数")
    medium_defects: int = Field(default=0, description="中等缺陷数")
    low_defects: int = Field(default=0, description="低优先级缺陷数")
    open_defects: int = Field(default=0, description="未解决缺陷数")
    resolved_defects: int = Field(default=0, description="已解决缺陷数")
    defect_density: Optional[float] = Field(None, description="缺陷密度")
    resolution_rate: Optional[float] = Field(None, description="解决率")


class QualityMetricsSummary(BaseModel):
    """质量指标汇总"""
    total_versions_analyzed: int = Field(default=0, description="分析的版本数")
    total_defects: int = Field(default=0, description="总缺陷数")
    average_defects_per_version: float = Field(default=0.0, description="平均缺陷数")
    critical_defect_rate: float = Field(default=0.0, description="严重缺陷率")
    overall_resolution_rate: float = Field(default=0.0, description="总体解决率")


# ========== 版本比较 Schema ==========

class VersionCompareInfo(BaseModel):
    """版本比较信息"""
    version1: Dict[str, Any] = Field(..., description="版本1信息")
    version2: Dict[str, Any] = Field(..., description="版本2信息")
    task_differences: Dict[str, Any] = Field(default_factory=dict, description="任务差异")
    defect_differences: Dict[str, Any] = Field(default_factory=dict, description="缺陷差异")
    summary: Dict[str, Any] = Field(default_factory=dict, description="比较摘要")


# ========== 版本影响分析 Schema ==========

class ImpactAnalysis(BaseModel):
    """影响分析模型"""
    version_info: Dict[str, Any] = Field(..., description="版本信息")
    direct_impact: Dict[str, Any] = Field(default_factory=dict, description="直接影响")
    indirect_impact: Dict[str, Any] = Field(default_factory=dict, description="间接影响")
    risk_assessment: Dict[str, Any] = Field(default_factory=dict, description="风险评估")


# ========== 版本变更历史 Schema ==========

class ChangeHistory(BaseModel):
    """变更历史模型"""
    timestamp: datetime = Field(..., description="变更时间")
    action: str = Field(..., description="变更操作")
    details: Dict[str, Any] = Field(default_factory=dict, description="变更详情")
    user_id: str = Field(..., description="操作用户ID")
    type: str = Field(..., description="变更类型")


# ========== 发布计划 Schema ==========

class ReleasePlan(BaseModel):
    """发布计划模型"""
    id: str = Field(..., description="计划ID")
    name: str = Field(..., description="计划名称")
    description: Optional[str] = Field(None, description="计划描述")
    version_ids: List[str] = Field(default_factory=list, description="版本ID列表")
    planned_date: datetime = Field(..., description="计划日期")
    environment: str = Field(..., description="发布环境")
    status: str = Field(..., description="计划状态")
    approval_status: str = Field(..., description="审批状态")
    created_by: str = Field(..., description="创建者ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    approved_by: Optional[str] = Field(None, description="审批者ID")
    approved_at: Optional[datetime] = Field(None, description="审批时间")


# ========== 版本依赖关系 Schema ==========

class VersionDependency(BaseModel):
    """版本依赖关系"""
    version_id: str = Field(..., description="版本ID")
    version_name: str = Field(..., description="版本名称")
    version_number: str = Field(..., description="版本号")
    status: str = Field(..., description="版本状态")
    relation_type: str = Field(..., description="关联类型")
    depth: int = Field(..., description="依赖深度")


class VersionDependencies(BaseModel):
    """版本依赖关系集合"""
    version: Dict[str, Any] = Field(..., description="版本信息")
    dependencies: List[VersionDependency] = Field(default_factory=list, description="依赖列表")
    total_dependencies: int = Field(default=0, description="依赖总数")
    max_depth_analyzed: int = Field(..., description="分析的最大深度")


# ========== 版本报告 Schema ==========

class VersionReport(BaseModel):
    """版本报告模型"""
    version_id: str = Field(..., description="版本ID")
    version_name: str = Field(..., description="版本名称")
    version_number: str = Field(..., description="版本号")
    version_status: str = Field(..., description="版本状态")
    project_id: Optional[str] = Field(None, description="项目ID")
    project_name: Optional[str] = Field(None, description="项目名称")
    summary: Dict[str, Any] = Field(..., description="汇总信息")
    test_execution_stats: Dict[str, Any] = Field(default_factory=dict, description="测试执行统计")
    report_type: str = Field(..., description="报告类型")
    generated_at: datetime = Field(default_factory=datetime.utcnow, description="生成时间")
    planned_release_date: Optional[datetime] = Field(None, description="计划发布时间")
    actual_release_date: Optional[datetime] = Field(None, description="实际发布时间")

